import os
from flask import Flask
from config.config import get_config
from service.chat.chat_server import ChatServer
from service.user.user_service import UserService
from models import db
from route.user_route import user_api
from utils.logger import get_logger

logger = get_logger(__name__)

def create_app(config_path: str = 'config/config.json'):
    logger.info("Starting application initialization...")
    app = Flask(__name__)
    logger.info("Flask application instance created")
    
    try:
        logger.info(f"Loading configuration from {config_path}")
        config = get_config(config_path)
        logger.info("Configuration loaded successfully")
    except Exception as e:
        logger.error(f"Failed to load configuration: {str(e)}")
        raise Exception(f"Failed to load configuration: {str(e)}")

    # 配置数据库
    logger.info("Configuring SQLite database")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///math_plan.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 配置会话密钥
    app.config['SECRET_KEY'] = config.get("secret_key", os.urandom(24).hex())
    
    # 初始化数据库
    logger.info("Initializing database")
    db.init_app(app)
    
    # 确保应用上下文中创建所有表
    with app.app_context():
        db.create_all()
        logger.info("Database tables created")

    # 初始化聊天服务
    logger.info("Initializing chat service")
    chat_service = ChatServer(config.get("openai_config"))

    app.chat_service = chat_service
    
    # 初始化用户服务
    logger.info("Initializing user service")
    app.user_service = UserService()

    # 注册API路由
    logger.info("Registering API routes")
    from route.chat_route import api
    app.register_blueprint(api)
    app.register_blueprint(user_api)
    
    logger.info("Application initialization completed")
    return app


app = create_app()


async def test(app):
    await app.chat_service.test()

# if __name__ == '__main__':
#     port = int(os.getenv('PORT', 5000))
#     host = '192.168.10.220'
#     logger.info(f"Starting server on {host}:{port}")
#     app.run(host=host, port=port, debug=True)

#     await test(app)


async def main():
    port = int(os.getenv('PORT', 5000))
    host = '192.168.10.220'
    logger.info(f"Starting server on {host}:{port}")
    app.run(host=host, port=port, debug=True)

    # await test(app)

import asyncio 
if __name__ == "__main__":
    asyncio.run(main())



